/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.logical.allhit.gui.action;

import com.logical.allhit.Kernel;
import com.logical.allhit.gui.MainFrom;
import com.logical.allhit.gui.model.AccountTableModel;
import com.logical.allhit.http.HTTPClient;
import com.logical.allhit.http.HTTPClientAdd;
import com.logical.allhit.setting.Account;
import com.logical.allhit.setting.Setting;
import com.logical.allhit.util.AddAttributeNew;
import com.logical.allhit.util.MsgLogger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 *
 * @author Sanjeet Jha
 */
public class TaskNew extends SwingWorker<Boolean, Integer> {

    private boolean[] selection;
    private int day, toDay;
    private boolean  formLast;
    private StartAction action;
    private MainFrom mainFrom;

    public TaskNew(boolean[] selection, StartAction action, MainFrom mainFrom, int day , int toDay, boolean fromLast) {
        this.selection = selection;
        this.action = action;
        this.mainFrom = mainFrom;
        this.day = day;
        this.toDay = toDay;
        this.formLast = fromLast;
    }

    @Override
    protected Boolean doInBackground() throws Exception {
        setProgress(0);
        String msg;
        AccountTableModel model = mainFrom.getAccountTableModel();

        for (int i = 0; i < model.getRowCount(); i++) {
            if ((Boolean) model.getValueAt(i, 0)) {
                Account account = model.getAccountAt(i);
                msg = "Select User " + account.getName();
                MsgLogger.getInstance().showMsg(msg);
                try {
                    if (HTTPClient.getInstance().login(account.getName(), account.getPassword(), account.getUsertype())) {
                        if (selection[0]) {//click Add
                            String mainPage = HTTPClient.getInstance().GET("http://" + Setting.getInstance().getHost() + "/pro_user/admin.php");
                            Document document = Jsoup.parse(mainPage);
                            Element form = document.getElementsByTag("form").first();
                            String userName = form.getElementById("emailId").attr("value");
                            String password = form.getElementById("passwords").attr("value");
                            HTTPClientAdd.getInstance().login(userName, password);

                            int totalAddClick = 0;
                            if (day == 0) {
                                ArrayList<String> urls = scanInbox(1);

                                for (int u = urls.size() - 1; u >= 0; u--) {
                                    clickAdd(urls.get(u));
                                    totalAddClick++;
                                    try {
                                        Thread.sleep(1000 * Setting.getInstance().getSleepTime());
                                    } catch (Exception e) {
                                        Logger.getLogger(Task.class.getName()).log(Level.WARNING, e.getMessage(), e);
                                    }
                                }
                                msg = "Total Add clicked " + totalAddClick;
                                MsgLogger.getInstance().showMsg(msg);
                            } else if(!formLast) {
                                for (int d = day; d >= toDay; d--) {
                                    ArrayList<AddAttributeNew> urls = geturl(d);
                                    for (int u = urls.size() - 1; u >= 0; u--) {
                                        try{
                                        clickAdd(urls.get(u).getUrl());
                                        } catch (Exception e){
                                            
                                        } finally {
                                            account.setTotalchild(urls.get(u).getPid());
                                            account.setRightchild(urls.get(u).getDate());
                                            account.setLeftchild(-1l);
                                        }
                                        totalAddClick++;
                                        try {
                                            Thread.sleep(1000 * Setting.getInstance().getSleepTime());
                                        } catch (Exception e) {
                                            Logger.getLogger(Task.class.getName()).log(Level.WARNING, e.getMessage(), e);
                                        }
                                    }
                                    Runtime.getRuntime().gc();
                                    System.gc();
                                }
                                msg = "Total Add clicked " + totalAddClick;
                                MsgLogger.getInstance().showMsg(msg);
                            }else if(formLast){
                                
                            }
                        }
                        if (selection[1]) {//Balance
//                        String balanceHtml = HTTPClient.getInstance().GET("http://202.87.47.29/~allhitde/pro_user/balanceinfo.php");
                            String balanceHtml = HTTPClient.getInstance().GET("http://" + Setting.getInstance().getHost() + "/pro_user/balanceinfo.php");
                            Document balanceDoc = Jsoup.parse(balanceHtml);
                            Element tr = balanceDoc.getElementsByTag("tr").last().getElementsByTag("td").last();
                            msg = "Balance for " + account.getName() + " are " + tr.text();
                            MsgLogger.getInstance().showMsg(msg);
                            account.setBalance(Float.parseFloat(tr.text()));
                            model.fireTableDataChanged();
                        }
//                        if (selection[2]) {//User Tree
//                            msg = "try to update user tree";
//                            MsgLogger.getInstance().showMsg(msg);
//                            String userTreeHtml = HTTPClient.getInstance().GET("http://" + Setting.getInstance().getHost() + "/pro_user/membertree.php?id=" + account.getUid());
//                            Document userTreeDoc = Jsoup.parse(userTreeHtml);
//                            Element td = userTreeDoc.getElementsByClass("table_cell").get(2);
//                            String text = td.text();
//                            //Left Users  : 4 Right Users : 3 Total Users : 7
//                            long lu = 0, ru = 0, tu = 0;
//                            String lString = text.substring(text.indexOf("Left Users  : ") + 15, text.indexOf("Right Users")).trim();
//                            if (lString.equals("")) {
//                                lString = "0";
//                            }
//                            lu = Long.parseLong(lString);
//                            String rString = text.substring(text.indexOf("Right Users : ") + 14, text.indexOf("Total Users")).trim();
//                            if (rString.equals("")) {
//                                rString = "0";
//                            }
//                            ru = Long.parseLong(rString);
//                            String tString = text.substring(text.indexOf("Total Users : ") + 14).trim();
//                            if (tString.equals("0")) {
//                                tString = "0";
//                            }
//                            tu = Long.parseLong(tString);
//                            account.setLeftchild(lu);
//                            account.setRightchild(ru);
//                            account.setTotalchild(tu);
//                            model.fireTableDataChanged();
//                            msg = "update user tree!";
//                            MsgLogger.getInstance().showMsg(msg);
//                        }
                        try {
                            Thread.sleep(1000 * Setting.getInstance().getSleepTime());
                            float curr = (float) i + 1;
                            int per = (int) ((curr / model.getRowCount()) * 100);
                            setProgress(per);
                        } catch (Exception e) {
                            Logger.getLogger(Task.class.getName()).log(Level.WARNING, e.getMessage(), e);
                        }
                        HTTPClient.getInstance().logout(account.getUsertype());
                        Runtime.getRuntime().gc();
                        System.gc();
                    } else {
                        MsgLogger.getInstance().showMsg("Loging fild for " + account.getName() + " try agin ....");
                        break;
                    }
                } catch (Exception e) {
                    Logger.getLogger(Task.class.getName()).log(Level.WARNING, e.getMessage(), e);
                }
                model.setValueAt(false, i, 0);
                model.fireTableDataChanged();
            }
        }
        msg = "End of process";
        setProgress(100);
        MsgLogger.getInstance().showMsg(msg);
        JOptionPane.showMessageDialog(Kernel.getInstance().getFrame(), msg);
        return true;
    }

    @Override
    protected void done() {
        super.done();
        action.setEnabled(true);
    }

    private ArrayList<String> scanInbox(int pageNo) {
        String msg = "Scaning Inbox page " + pageNo;
        boolean isfine = false;
        MsgLogger.getInstance().showMsg(msg);
        ArrayList<String> urls = new ArrayList<String>();
        ArrayList<String> pids = new ArrayList<String>();
//        String inbox = HTTPClientAdd.getInstance().GETAdd("http://202.87.47.29/~allhitdl/deals/promostatus.php?page=" + pageNo + "&panelid=0");
        String inbox = HTTPClientAdd.getInstance().GETAdd("http://promos.allhitdeals.com/deals/promostatus.php?page=" + pageNo + "&panelid=0");
        Document inboxDocument = Jsoup.parse(inbox);
        Element table = inboxDocument.getElementsByClass("box1").first();
        Elements imgs = table.getElementsByTag("img");
        for (Element img : imgs) {
            if (img.attr("src").equals("images/Pending.png")) {
                isfine = true;
                Element tr = img.parent().parent();
                Element input = tr.child(0).child(0);
                if (input.attr("name").equals("pid")) {
                    pids.add(input.attr("value"));
                }
            }
        }

        //http://202.87.47.29/~allhitdl/deals/inbox.php?page=2&panelid=0
//        inbox = HTTPClientAdd.getInstance().GETAdd("http://202.87.47.29/~allhitdl/deals/inbox.php?page=" + pageNo + "&panelid=0");
        inbox = HTTPClientAdd.getInstance().GETAdd("http://promos.allhitdeals.com/deals/inbox.php?page=" + pageNo + "&panelid=0");
        inboxDocument = Jsoup.parse(inbox);
        table = inboxDocument.getElementsByClass("box1").first();
        Elements inputs = table.getElementsByTag("input");
        for (Element input : inputs) {
//            if (input.attr("value").equals("images/Pending.png")) {
            if (pids.contains(input.attr("value"))) {
                Element td = input.parent();
                Element a = td.child(0);
//                urls.add("http://202.87.47.29/~allhitdl/" + a.attr("href"));  
//                urls.add("http://202.87.47.29/~allhitdl/deals/" + a.attr("href"));
                urls.add("http://promos.allhitdeals.com/deals/" + a.attr("href"));
//                urls.add("http://www.allhitdeals.net/deals/" + a.attr("href"));
            }
        }


        if (isfine && pageNo < 32) {
            ArrayList<String> urls1 = scanInbox(++pageNo);
            urls.addAll(urls1.subList(0, urls1.size()));
            pageNo--;
        }
        msg = "Scaning complet of page " + pageNo;
        MsgLogger.getInstance().showMsg(msg);
        return urls;
    }

//    private ArrayList<String> geturl(int pageNo) {
//        String msg = "Scaning Inbox page " + pageNo;
//        MsgLogger.getInstance().showMsg(msg);
//        ArrayList<String> urls = new ArrayList<String>();
//
//        String inbox = HTTPClientAdd.getInstance().GETAdd("http://promos.allhitdeals.com/deals/inbox.php?page=" + pageNo + "&panelid=");
//        Document inboxDocument = Jsoup.parse(inbox);
//        Element table = inboxDocument.getElementsByClass("box1").first();
//        Elements inputs = table.getElementsByTag("input");
//        for (Element input : inputs) {
//            Element td = input.parent();
//            Element a = td.child(0);
//            urls.add("http://promos.allhitdeals.com/deals/" + a.attr("href"));
//        }
//        msg = "Scaning complet of page " + pageNo;
//        MsgLogger.getInstance().showMsg(msg);
//        return urls;
//    }
    
    private ArrayList<AddAttributeNew> geturl(int pageNo) {
        String msg = "Scaning Inbox page " + pageNo;
        MsgLogger.getInstance().showMsg(msg);
        ArrayList<AddAttributeNew> urls = new ArrayList<AddAttributeNew>();

        String inbox = HTTPClientAdd.getInstance().GETAdd("http://promos.allhitdeals.com/deals/inbox.php?page=" + pageNo + "&panelid=");
        Document inboxDocument = Jsoup.parse(inbox);
        Element table = inboxDocument.getElementsByClass("box1").first();
        Elements inputs = table.getElementsByTag("input");
        for (Element input : inputs) {
            AddAttributeNew addAttributeNew = new AddAttributeNew();
            addAttributeNew.setPid(Long.parseLong(input.attr("value")));
            Element td = input.parent();
            Element a = td.child(0);
            addAttributeNew.setUrl("http://promos.allhitdeals.com/deals/" + a.attr("href"));
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            try{
                long date = dateFormat.parse(td.parent().child(1).text()).getTime();
                addAttributeNew.setDate(date);
            } catch(ParseException e){
                
            }
            urls.add(addAttributeNew);
        }
        msg = "Scaning complet of page " + pageNo;
        MsgLogger.getInstance().showMsg(msg);
        return urls;
    }

    private void clickAdd(String url) {
        String inbox = HTTPClientAdd.getInstance().GETAdd(url);
        Document inboxDocument = Jsoup.parse(inbox);
        Element table = inboxDocument.getElementsByClass("formbg").first();
        Element form = table.getElementsByTag("form").first();
        Element imagecode = form.getElementById("captchaimg");
        String msg = "cilck add on " + form.attr("action");
//        HTTPClientAdd.getInstance().addClick("http://202.87.47.29/~allhitdl/"+form.attr("action"));    
//        HTTPClientAdd.getInstance().addClick("http://202.87.47.29/~allhitdl/deals/"+form.attr("action"),imagecode.attr("src"),url);
        HTTPClientAdd.getInstance().addClick("http://promos.allhitdeals.com/deals/" + form.attr("action"), imagecode.attr("src"), url);
        MsgLogger.getInstance().showMsg(msg);
    }
}
